<template>
	<view>
		<j-doorbell v-show="show" :show="show" ref="doorbellCall" :alarmInfo="doorLockInfo" :hangUp="isHangUp" @answerClick="answerCall" @hangUp="hangUp"></j-doorbell>
	</view>
</template>

<script>
	const { getBeforeDay } = require('@/utils/util.js');
	export default {
		data() {
			return {
				date:'',
				alarmId:'',
				device:{
					token:'',
					deviceNo:'',
					deviceName:'',
					alarmEvent:'',
					secondAlarmEvent:'',
				},
				doorLockInfo:{
					secondAlarmEvent:''
				},
				isHangUp:false,
                show: false,
				isOnLoad:false,
				secondAlarmEvent:''
			}
		},
		onHide() {
            this.$refs.doorbellCall.closePopup(3)
            // this.show = false
            this.$logs({info:'公众号跳转-onHide',res: this.show})
			this.isOnLoad = false
		},
		onUnload() {
            uni.$off('backCloudMsg')
            this.$refs.doorbellCall.closePopup(3)
            this.show = false
            this.$logs({info:'公众号跳转-onUnload',res: this.show})
			this.isOnLoad = false
		},
		onShow() {
			uni.$on('backCloudMsg',(data)=>{
                this.$refs.doorbellCall.closePopup(3)
				uni.switchTab({
					url:'/jvss/pages/device/home'
				})
                this.$logs({info: 'onShow跳转回首页'})
			})
            // if(this.$refs.doorbellCall.audioCtx) {
            //     this.$refs.doorbellCall.audioCtx.play()
            // }
			let scene = wx.getLaunchOptionsSync()
			console.log('场景==',scene)
			this.$logs({info:'公众号消息跳转页场景onShow',data:scene},'error')
            // mqtt断链超过1分钟重新订阅
            const now = Date.now()
            const prev = uni.getStorageSync('mqttCloseTemp')
            if(prev&&now-prev>=60*1000) {
                uni.$on('mqttConnectSuccess', () => {
                    this.sendWebsocketInfo(this.device.deviceNo)
                })
            }
			if(!this.isOnLoad){
				if(Object.keys(this.device).length>0) {
					this.device = uni.getStorageSync('officialAccountData')
                    this.$logs({info: '获取本地device得值', device: uni.getStorageSync('officialAccountData')})
					this.getAdminToken()

				}
			}
            this.$logs({info: '获取本地device得值', device: uni.getStorageSync('officialAccountData')})

			
		},
		onLoad(opt) {
            this.$logs({info: '加载的opt信息', opt: opt})
			console.log('公众号消息跳转===',opt);
			// let data = {
			// 	adminToken: "Ffbw/cDagD75EU8HYHMy7kxqBngyaelqozPLKDZe9lw=",
			// 	alarmEvent: "DoorLockCall",
			// 	alarmId: "231024184209386",
			// 	date: "1695608138",
			// 	devPassWord: "",
			// 	devUserName: "admin",
			// 	deviceName: "测试名称",
			// 	deviceNo: "10000093761092843328",
			// 	SerialNumber:'10000093761092843328',
			// 	AlarmID:'231024184209386'
   //              // 230925154701272
			// }
			// let res = encodeURIComponent(JSON.stringify(data))
			// console.log('data =====',res, Date.now());
			// let path = `%7B%22adminToken%22%3A%22nYs5FlEYo97fu0lorBDNgVwizikUG9rk1C3ZPAQiGPI%3D%22%2C%22alarmEvent%22%3A%22DoorLockCall%22%2C%22alarmId%22%3A%22236825916%22%2C%22date%22%3A%221686164356%22%2C%22devPassWord%22%3A%22%22%2C%22devUserName%22%3A%22admin%22%2C%22deviceName%22%3A%22%E6%B5%8B%E8%AF%95%E5%90%8D%E7%A7%B0%22%2C%22deviceNo%22%3A%22bdb2fa94d9e3e022%22%7D`

            // uni.showLoading()
            if(opt.deviceNo){   //兼容之前的形式
                this.device.deviceNo = opt.deviceNo
                this.device.deviceName = opt.deviceName
                this.device.alarmEvent = opt.alarmEvent
                this.device.alarmId = opt.alarmId
                this.device.AlarmID = opt.alarmId
                this.device.SerialNumber = opt.deviceNo
                this.device.pid = opt.pid
				this.device.secondAlarmEvent = opt.secondAlarmEvent
				this.secondAlarmEvent = opt.secondAlarmEvent
                this.alarmId = opt.alarmId
                this.date = Number(opt.date)
                if(opt.devUserName){
                    this.device.adminToken =  opt.adminToken
                    this.device.devUserName = opt.devUserName
                    this.device.devPassWord = opt.devPassWord
                }
                this.setCache(opt)
                this.getAdminToken()
                this.$logs({info:'公众号消息跳转1',data:opt, show: this.show},'error')
            }else{
                if(Object.keys(opt).length !=0 && opt.data){
                    let enData = decodeURIComponent(opt.data)
                    this.device = JSON.parse(enData)
                    this.device.AlarmID = this.device.alarmId
                    this.device.SerialNumber = this.device.deviceNo
					this.secondAlarmEvent = this.device.secondAlarmEvent
                    console.log('解析数据==',this.device);
                    this.date = Number(this.device.date)
                    this.setCache(opt)
                    this.getAdminToken()
                    this.$logs({info:'公众号跳转消息2',res: this.show, data: opt})
                }else{
                    this.device = uni.getStorageSync('officialAccountData')
                    this.$logs({info:'公众号跳转消息-this.device', data: opt, show: this.show, device: this.device})
                    if(Object.keys(this.device).length>0) this.getAdminToken()
                    this.$logs({info:'公众号跳转消息3',data: opt, device: this.device, show: this.show})
                }
                this.$logs({info:'公众号跳转消息4',data:opt,device:this.device},'error')
            }
			this.isOnLoad = true
		},
		methods: {
            //websocket发送消息
            sendWebsocketInfo(sns) {
                let topic = `/device/${sns}`;
                let newTopics = `/device/${sns}/alarmEvent`;
                // 订阅单个设备
                getApp().globalData.mqtt.subscribe(topic)
                getApp().globalData.mqtt.subscribe(newTopics)
                this.$logs({info: '公众号跳转超过一分钟-订阅单个设备', topic, newTopics})
            },
			//设置缓存
			setCache(opt){
				if(Object.keys(opt).length>0){
					uni.setStorageSync('officialAccountData',this.device)
				}
				let scene = wx.getLaunchOptionsSync()
				this.$logs({info:'公众号消息跳转-setCache',opt:opt,data:this.device,scene:scene},'error')
			},
			answerCall(data){
				console.log('接听===',data);
			},
			hangUp(data){
                this.$logs({info: '门铃来电hangUp', data: data})
				let url = '/jvss/pagesDevice/device/device-live/door-lock/cloudMsg?type=3&device='+encodeURIComponent(JSON.stringify(this.device))
				uni.reLaunch({
					url:url
				})
                this.$refs.doorbellCall.closePopup(3)
                this.show = false
                this.$logs({info:'公众号跳转-hangUp',res: this.show})
			},
			// 获取设备最新的adminToken
			getAdminToken(){
				let data = {
					deviceNo:this.device.deviceNo,
					isLatest:true
				}
				getApp().globalData.api.getDeviceTokenLocal(data, (result) => {
				    console.log('获取设备adminToken:', result);
					this.device.adminToken = result.adminToken
					this.device.devUserName = result.devUserName
					this.device.devPassWord =  result.devPassWord
					this.getDeviceToken([this.device.deviceNo])
				});
			},
			//获取设备token
			getDeviceToken(sns) {
			    const data = {
			        sns: sns
			    };
			    getApp().globalData.api.getDeviceToken(data, (result) => {
			        console.log('获取设备token:', result);
					this.device.token = result[0].token
                    this.$logs({info:'公众号跳转获取最新的adminToken',res:this.show})
					this.getDeviceStatus([result[0].token])
			    });
			},
			// 获取设备状态
			getDeviceStatus(tokenList) {
				const data = {
					token: tokenList
				};
				getApp().globalData.api.getDeviceStatus(data, (result) => {
					this.$logs({info:'公众号消息跳转获取设备状态',res:result, device: this.device},'error')
                    console.log(result[0], '获取设备状态的信息')
					this.device.status = result[0]
					// this.doorLockInfo  = this.device
					let item = result[0]
					let paramUrl = `?type=3&device=${encodeURIComponent(JSON.stringify(this.device))}`
					let msgUrl = '/jvss/pagesDevice/device/device-live/door-lock/cloudMsg'+paramUrl
					let liveUrl = '/jvss/pagesDevice/device/device-live/door-lock/live1'+paramUrl
					let liveLexinUrl = '/jvss/pagesDevice/device/device-live/door-lock/live-lexin'+paramUrl
					let liveLexin2Url = '/jvss/pagesDevice/device/device-live/door-lock/live-lexin2'+paramUrl
					let liveFamilyUrl  = '/jvss/pagesDevice/device/device-live/door-lock/live-familyCall'+paramUrl
					let url = msgUrl
					
					let tapUrl = ''
					let time = parseInt(new Date().getTime()/1000)
					let constant = getApp().globalData.constant;
					let LOCK3 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK3;
					let LOCK8 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK8;
					let LOCK4 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK4; // 博克乐鑫XM650主PID live-lexin2
					let LOCK19 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK19 //博克乐鑫XM650派生PID live-lexin2
					
					if(this.device.alarmEvent == 'DoorLockCall'){
                        this.$logs({info: '公众号跳转-是门铃来电', res: result, device: this.device})
						if(time < Number(this.date+6000000000)){
                            this.$logs({info: '公众号跳转门铃来电-时间间隔', res: result, device: this.device, date: this.date})
							if(item.status === 'online' ){
								if(item.wakeUpStatus === '0' ){
									if(item.wakeUpEnable === '0' ){
										//深度休眠 手动唤醒
										console.log('深度休眠 手动唤醒');
                                        this.$logs({info:'公众号跳转深度休眠 手动唤醒',res:this.show})
									}else{
										//浅休眠 可以唤醒
										// url = '/jvss/pagesDevice/device/device-live/door-lock/live-lexin?type=3&device='+encodeURIComponent(JSON.stringify(this.device))
										// if(this.device.pid == LOCK3 || this.device.pid == LOCK8){
										// 	url = '/jvss/pagesDevice/device/device-live/door-lock/live1?type=3&device='+encodeURIComponent(JSON.stringify(this.device))
										// }
										// console.log('浅休眠 可以唤醒');

										this.isHangUp = false
										this.doorLockInfo  = this.device

                                        // this.show = true
                                        setTimeout(() => {
                                            uni.hideLoading()
                                        }, 500)
                                        this.show = true
										this.$refs.doorbellCall.openPopup()
                                        this.$refs.doorbellCall.setAudioUrl()
                                        this.$logs({info:'公众号消息跳转开启门铃来电弹窗-浅休眠', show: this.show})
                                        console.log('公众号消息跳转开启门铃来电弹窗1')
										return
									}
								}else if(item.wakeUpStatus === '1'){
									//已唤醒 在线
									url = liveLexinUrl
									if(this.device.pid == LOCK3 || this.device.pid == LOCK8){
										url = liveUrl
									}else if(this.device.pid == LOCK4 || this.device.pid == LOCK19){
										url = liveLexin2Url
									}
									console.log('已唤醒 在线');
									this.isHangUp = false
									this.doorLockInfo  = this.device
									this.doorLockInfo.secondAlarmEvent = this.secondAlarmEvent
									this.show = true
									this.$refs.doorbellCall.openPopup()
									this.$refs.doorbellCall.setAudioUrl()
									this.$logs({info:'公众号消息跳转开启门铃来电弹窗-在线', show: this.show})
									console.log('公众号消息跳转开启门铃来电弹窗2')
									return
								}else if(item.wakeUpStatus === '2'){
									// 准备休眠中
									console.log('准备休眠中');
                                    this.$logs({info:'公众号跳转准备休眠中',res:this.show})
								}
                                this.$logs({info:'公众号跳转item.status === online',res:this.show})
							}else{
								//离线
                                this.$logs({info:'公众号跳转设备离线',res:this.show})
							}
						}
					}
					// console.log('跳转');
					uni.reLaunch({
						url:url
					})
					this.$refs.doorbellCall.closePopup(3)
                    console.log('公众号消息跳转开启门铃来电弹窗3')
					console.log('订阅处理后的设备列表', this.device,this.date,time);
					// #ifdef MP-WEIXIN
					this.$logs({info:'公众号消息跳转3',data:this.device,currenTime:time,eventTime:this.date, url: url})
					// #endif
				});
			},
			//获取消息列表
			getMsgList(callback) {
				let token = this.device.token
				let startTime = getBeforeDay(0) + ' ' + '00:00:00'
				let endTime = getBeforeDay(0) + ' ' + '23:59:59'
				let data = {
					sn: this.device.deviceNo,
					startTime:startTime,
					endTime: endTime,
					pageSize: 20,
					pageNum: 1
				}
				getApp().globalData.api.getLockAlarmMSgList(data, token, (result) => {
					callback(result.AlarmArray)
				})
			}
		}
	}
</script>

<style scoped>

</style>
